package top.went.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.CustomerDao;
import top.went.db.dao.UserDao;
import top.went.db.mapper.CustomerMapper;
import top.went.exception.InputException;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.CustomerEntity;
import top.went.pojo.SaleOppEntity;
import top.went.pojo.UserEntity;
import top.went.utils.Combines;
import top.went.vo.Code;
import top.went.vo.CustomerVo;
import top.went.vo.PageEntity;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.*;

@Service
@Transactional(value = "transactionManager",rollbackFor = ServiceException.class)
public class CustomerService {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private SaleOppService saleOppService;
    @Autowired
    private UserDao userDao;

    /**
     * 新增客户
     *
     * @param customerEntity
     * @return
     * @throws ServiceException
     */
    public Code addCustomer(CustomerEntity customerEntity) throws ServiceException {
        try {
            if (customerEntity != null) {
                   List<CustomerEntity> customerEntityList = customerDao.findAll();
                   for(CustomerEntity customerEntity1:customerEntityList){
                       if(customerEntity1.getCusName().equals(customerEntity.getCusName())){
                           System.out.println("aaaaaa");
                           return Code.fail("客户名称重复");
                       }else if(customerEntity1.getCusAbbreviation().equals(customerEntity.getCusAbbreviation())){
                           System.out.println("bbbbbb");
                           return Code.fail("客户简称重复");
                       }
                   }
                    boolean result = customerDao.save(customerEntity) != null;
                    if (result == true) {
                        return Code.success("新建客户成功");
                    } else {
                        return Code.fail("新建客户失败");
                    }
            }
            return Code.fail("新建客户参数错误");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新建客户异常");
        }
    }

    /**
     * 4
     * 逻辑删除客户
     *
     * @param id
     * @return
     * @throws ServiceException
     */
    public Code deleteCus(Integer id) throws ServiceException {
        try {
            if (id != null) {
                CustomerEntity customerEntity = customerDao.findOne(id);
                customerEntity.setCusIsDelete(0L);
                customerDao.save(customerEntity);
                return Code.success("删除客户成功");
            }
            return Code.fail("参数错误");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("删除客户异常");
        }
    }

    /**
     * 获取客户列表
     *
     * @return
     * @throws ServiceException
     */
    public PageEntity<CustomerVo> getCusList(Integer pageSize,Integer pageNum) throws ServiceException {
        try {
            System.out.println(pageSize + "      "+ pageNum);
            List<CustomerEntity> customerEntityList =  customerDao.findAllByCusIsDeleteOrderByCusIdDesc(1L,new PageRequest(pageNum,pageSize));

            System.out.println(customerEntityList.size());
            List<CustomerVo> customerVoList = new ArrayList<CustomerVo>();
            for(CustomerEntity c: customerEntityList){
                CustomerVo customerVo = new CustomerVo(c.getCusName(),c.getCusAbbreviation(),c.getCusType(),"张三",c.getCusLifecycle(),c.getCusLevel(),c.getCusIndustry(),c.getCusStage());
                customerVoList.add(customerVo);
            }
            Long total = customerDao.count();
            return new PageEntity<CustomerVo>(total,customerVoList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取客户列表异常");
        }
    }

    /**
     * 高级查询
     * @param customerEntity
     * @return
     * @throws ServiceException
     */
    public PageInfo fuzzySearch(Integer pageSize,Integer pageNum,CustomerEntity customerEntity) throws ServiceException{
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<CustomerEntity> customerEntityList = customerMapper.findByParam(customerEntity);
            List<CustomerVo> customerVoList = new ArrayList<>();
            for(CustomerEntity c:customerEntityList){
                CustomerVo customerVo = new CustomerVo(c.getCusName(),c.getCusAbbreviation(),c.getCusType(),"张三",c.getCusLifecycle(),c.getCusLevel(),c.getCusIndustry(),c.getCusStage());
                customerVoList.add(customerVo);
            }
            PageInfo pageInfo =new PageInfo();
            pageInfo.setList(customerVoList);
            return pageInfo;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("查询异常");
        }
    }

    /**
     * 得到单个客户
     *
     * @param id
     * @return
     * @throws ServiceException
     */
    public CustomerEntity getOneCus(Integer id ) throws ServiceException {
        try {
            CustomerEntity customerEntity = customerDao.findByCusId(id);
            return customerEntity;
        } catch (Exception e) {
            throw new ServiceException("获取客户异常");
        }
    }

    /**
     * 更新某个客户
     * @param
     * @param customerEntity
     * @return
     * @throws ServiceException
     */
    public Code updateCus(CustomerEntity customerEntity) throws ServiceException {
        try {
            if (customerEntity != null) {
                customerEntity.setCusIsDelete(1L);
                customerDao.save(customerEntity);
                return Code.success("修改成功");
            }
            return Code.fail("参数错误");
        } catch (Exception e) {
            throw new ServiceException("更新客户异常");
        }
    }

    public PageEntity<CustomerEntity> findAllByKid(Integer pageSize,Integer pageNum,CustomerVo customerVo) throws ServiceException{
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<CustomerEntity> customerEntityList = customerMapper.findByKids(customerVo);
            PageEntity pageEntity = new PageEntity(((com.github.pagehelper.Page)customerEntityList).getTotal(),customerEntityList);
            return pageEntity;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("获取客户数据异常");
        }

    }

    public void deleteProductAll(Long[] ids) throws ServiceException {
        try{
            for (int i=0;i<ids.length;i++){
                CustomerEntity customerEntity = customerDao.findOne(ids[i].intValue());
                customerEntity.setCusIsDelete(0L);
                customerDao.save(customerEntity);
            }
        }catch (Exception e){
            throw new ServiceException("删除异常");
        }

    }



    public String[] getFiles(Integer id){
        CustomerEntity customerEntity = customerDao.findByCusId(id);
        String files = customerEntity.getCusFiles();
        String fileName[] = null;
        if(files ==null ||files == ""){
            return fileName;
        }else{
            fileName = files.split(",");
            System.out.println(fileName.length);
        }
        System.out.println(files);
        return fileName;
    }


    public Code saveThree(Object[] three){
        for(int i=0;i<three.length;i++){
            System.out.println(three[i]);
        }
        CustomerEntity customerEntity = customerDao.findByCusId(Integer.parseInt(three[0].toString()));
        customerEntity.setCusDetermine(three[1].toString());
        customerEntity.setCusClass(three[2].toString());
        customerEntity.setCusSignDate(three[3].toString());
        return Code.success();
    }


    public SaleOppEntity getOneSaleOpp(Integer id){
        List<SaleOppEntity> saleOppEntities = saleOppService.loadAllByCusId((long)id);
        if(saleOppEntities.size() == 0){
            return null;
        }
        return saleOppEntities.get(0);
    }


    public long countByUser(Long userId)throws ServiceException{
        try {
            return customerDao.countAllByTbUserByUserId(userDao.findUserByOne(0L,userId));
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }
    public long countByMonth()throws ServiceException{
        try {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            return customerDao.countAllByMonth(year, month);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }


}
